<script setup>
import { ref, onMounted } from 'vue'
import { identifyPage, ImeiAll, Wangge, delGroupImg, identifyCount, quickIdentify, CameraWorker, layDevice } from '@/utils/api.js'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import wlsLarge from '@/components/common/wls-large.vue'
import wlsUpload from '@/components/common/wls-upload.vue'
import { Search } from '@element-plus/icons-vue';
const router = useRouter();
let areaId = '';
let username = '';
let imeiList = [];
let wgList = [];
const wlsupload = ref(null);
const cameraEnvirId = ref('');
const wangge = ref('');
const identifyType = ref('未鉴定');
const date = ref('');
const keywords = ref('');
const total = ref({
    delNum: 40,
    identifyNum: 10714,
    imageNum: 4,
    notIdentifyNum: 17,
    speciesNum: 10674,
    sum: 10691,
    videoNum: 13
})
const iswl = ref(false);
const wlm = ref([]);
const gip = ref([]);
const totalElements = ref(0);
let pageNum = 1;
const currentPage = ref(1);

const getidentifyCount = async () => {
    let res = await identifyCount(areaId)
    if (res.code == '200') {
        total.value = res.data;
    }
}

const getImeiAll = async () => {
    let res = await ImeiAll(areaId)
    if (res.code == '200') {
        imeiList = res.data;
    }
}

const getWangge = async () => {
    let res = await Wangge(areaId)
    if (res.code == '200') {
        wgList = res.data;
    }
}

const quick = async (data) => {
    if (data.aiResult != null) {
        let str = data.aiResult.split('#')[0];
        ElMessageBox.confirm(
            '确定要将“' + str + '”当作识别结果?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(() => {
                let params = {
                    "groupId": data.groupId,
                    "identifyPeople": username,
                    "speciesName": str
                }
                quickIdentify(params).then(res => {
                    if (res.code == '200') {
                        ElMessage({
                            type: 'success',
                            message: '已鉴定',
                        })
                        getgroupImgPage();
                        getidentifyCount();
                    }
                })
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消鉴定',
                })
            })
    }

}

const formatProcessingTime = (data) => {
    if (data != null && data != '') {
        let datetime = new Date(data);
        let year = datetime.getFullYear();
        let month = datetime.getMonth() + 1;
        let date = datetime.getDate();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        return year + "-" + month + "-" + date;
    } else {
        return ""
    }
}

const scl = () => {
    pageNum = 1;
    currentPage.value = 1;
    getgroupImgPage();
}

const getgroupImgPage = async () => {
    let params = '?areaId=' + areaId + '&cameraEnvirId=' + cameraEnvirId.value + '&wangge=' + wangge.value + '&identifyType=' + identifyType.value + '&date=' + formatProcessingTime(date.value) + '&keywords=' + keywords.value + '&pageNum=' + pageNum + '&pageSize=10'
    let res = await identifyPage(params);
    if (res.code == '200') {
        gip.value = res.data.content;
        totalElements.value = res.data.totalElements;
    }
};

const delGroupImgPage = (data, x) => {
    console.log(data);
    ElMessageBox.confirm(
        '确定要永久删除该文件吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let params = '?groupId=' + data.groupId + '&userName=' + username;
            delGroupImg(params).then(res => {
                if (res.code == '200') {
                    getgroupImgPage()
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                } else {
                    ElMessage({
                        type: 'info',
                        message: res.data.message,
                    })
                }

            })
                .catch(err => {
                    ElMessage({
                        type: 'info',
                        message: '网络异常',
                    })
                })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const goaut = (data) => {
    let name = '实时相机';
    let hisa = {
        pageNum: pageNum,
        currentPage: currentPage.value,
        cameraEnvirId: cameraEnvirId.value,
        wangge: wangge.value,
        identifyType: identifyType.value,
        date: formatProcessingTime(date.value),
        keywords: keywords.value
    }
    window.sessionStorage.setItem('hisa', JSON.stringify(hisa));
    router.push({ path: '/realTimeCamera/wlsauthenticate', query: { name: name, groupId: data.groupId, group: 'good' } });
}
const gour = () => {
    let name = '实时相机';
    router.push({ path: '/realTimeCamera/wlsuploadrecord', query: { name: name } });
}


const handleSizeChange = (val) => {
    pageNum = val;
    getgroupImgPage();
};

const openLarge = (data) => {
    wlm.value = data;
    iswl.value = true;
};

const getnewcar = () => {
    getgroupImgPage();
}

// 放置相机
import locationMap from '@/components/common/locationMap.vue';
import wlsPopup from '@/components/common/wls-popup.vue';
let Worker = [];
const isadd = ref(false);
const olm = ref(null);

const ruleForm = ref({
    "areaId": "",
    "imei": "",
    "deviceType": 1,
    "layTime": "",
    "planRecovDate": "",
    "lon": "",
    "lat": "",
    "altitude": "",
    "label": "",
    "layUser": "",
    "envirType": "",
    "smallEnvir": "",
    "remark": ""
});
const ruleFormRef = ref(null);

const ruleForms = ref({
    "id": "",
    "deviceType": 1,
    "recoveryDate": "",
    "recovUser": "",
    "damageDegree": "",
    "dumpEnergy": "",
    "freeMemory": "",
    "recycled": false,
    "changeCardId": ""
});

const addcarmelm = () => {
    for (let key in ruleForm.value) {
        ruleForm.value[key] = ''
    }
    isadd.value = true;
    setTimeout(function () {
        olm.value.initmap()
    }, 500)
}

const validateCoordinates = (lon, lat) => {
    lon = parseFloat(lon);
    lat = parseFloat(lat);

    if (!isNaN(lon) && !isNaN(lat) && lon >= -180 && lon <= 180 && lat >= -90 && lat <= 90 && lon !== 0 && lat !== 0) {
        return true; // 符合要求
    } else {
        return false; // 不符合要求
    }
}

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleForm.value.imei == null || ruleForm.value.imei == '') {
                ElMessage({
                    message: '请填写相机编号',
                    type: 'warning'
                })
                return false
            }
            if (!validateCoordinates(ruleForm.value.lon, ruleForm.value.lat)) {
                ElMessage({
                    message: '经纬度是必填项，请输入正确的经纬度',
                    type: 'warning',
                })
                return false
            }

            let params = JSON.parse(JSON.stringify(ruleForm.value));
            params.areaId = areaId;
            params.deviceType = 0;

            params.layTime = fptml(params.layTime);
            params.planRecovDate = fptml(params.planRecovDate);

            layDevice(params).then(res => {
                if (res.code == '200') {
                    getImeiAll();
                    resetForm(ruleFormRef.value);
                    ElMessage({
                        message: '布设完成',
                        type: 'success'
                    })
                } else {
                    ElMessage({
                        type: 'info',
                        message: res.msg
                    })

                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
};
const resetForm = (formEl) => {
    if (!formEl) return
    isadd.value = false;
    formEl.resetFields()
};

const getCameraWorker = async () => {
    let res = await CameraWorker(areaId)
    if (res.code == '200') {
        Worker = res.data;
    }
};

const getlna = async (item) => {
    ruleForm.value.lon = item[0];
    ruleForm.value.lat = item[1];
}

const fptml = (data) => {
    if (data != null && data != '') {
        let datetime = new Date(data);
        let year = datetime.getFullYear();
        let month = datetime.getMonth() + 1;
        let date = datetime.getDate();
        let Hours = datetime.getHours();
        let Minutes = datetime.getMinutes();
        let Seconds = datetime.getSeconds();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        if (Hours >= 1 && Hours <= 9) {
            Hours = "0" + Hours;
        }
        if (Minutes >= 0 && Minutes <= 9) {
            Minutes = "0" + Minutes;
        }
        if (Seconds >= 1 && Seconds <= 9) {
            Seconds = "0" + Seconds;
        }
        return year + "-" + month + "-" + date + " " + Hours + ":" + Minutes + ":" + Seconds;
    } else {
        return ""
    }
}

onMounted(() => {
    areaId = window.sessionStorage.getItem('areaId');
    username = window.sessionStorage.getItem('zhName');
    setTimeout(function () {
        if (window.sessionStorage.getItem('hisa') != null) {
            let data = JSON.parse(window.sessionStorage.getItem('hisa'));
            identifyType.value = data.identifyType;
            date.value = data.date == '' ? '' : new Date(data.date);
            keywords.value = data.keywords;
            cameraEnvirId.value = data.cameraEnvirId;
            wangge.value = data.wangge;
            pageNum = data.pageNum;
            currentPage.value = data.currentPage;
            getgroupImgPage();
            window.sessionStorage.removeItem('hisa')
        } else {
            getgroupImgPage();
        }
    }, 500)

    getCameraWorker();
    getImeiAll();
    getWangge();
    getidentifyCount();
});

</script>
<template>
    <div class="wls-aut">
        <div class="wls-aut-title">
            <div style="font-weight: 700;"><span>实时相机</span></div>
            <div style="margin-left: 0.16rem;"><span>总计</span>
                <span style="color: var(--wls-color);margin-left: 0.08rem;">{{ total.sum }}张</span>
            </div>
            <div style="margin-left: 0.16rem;"><span>已鉴定</span>
                <span style="color: var(--wls-color);margin-left: 0.08rem;">{{ total.identifyNum }}</span>
                <span style="color: #AAA;">（有物种:{{ total.speciesNum }}/已删除:{{ total.delNum }}）</span>
            </div>
            <div style="margin-left: 0.16rem;"><span>未鉴定</span>
                <span style="color: var(--wls-color);margin-left: 0.08rem;">{{ total.imageNum }}照片/{{ total.videoNum
                    }}视频</span>
            </div>

            <div class="wls-aut-title-btn" v-if="false" @click.stop="gour" style="right: 1rem;">
                <svg class="wls-icon" aria-hidden="true">
                    <use xlink:href="#icon-shangchuanjilu"></use>
                </svg>
                <span style="margin-left: 0.08rem;">上传记录</span>
            </div>

            <div class="wls-aut-title-btn" style="right: 1rem;">
                <!-- <svg class="wls-icon" aria-hidden="true">
                        <use xlink:href="#icon-fangzhixiangji"></use>
                    </svg> -->
                <i style="color: var(--wls-color);" class="icon iconfont icon-fangzhixiangji"></i>
                <span class="wlsc" @click.stop="addcarmelm()" style="margin-left: 0.08rem;">放置相机</span>
            </div>

            <div class="wls-aut-title-btn" style="right: .24rem;" @click.stop="wlsupload.open('实时相机')">
                <svg class="wls-icon" aria-hidden="true">
                    <use xlink:href="#icon-shangchuan"></use>
                </svg>
                <span style="margin-left: 0.08rem;">上传</span>
            </div>
        </div>

        <div class="wls-aut-container">
            <div class="bcb">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-select v-model="cameraEnvirId" style="width: 100%;" @change="scl()" class="m-2" filterable
                            clearable placeholder="请选择相机编号" size="large">
                            <el-option v-for="(i, index) in imeiList" :key="i.id" :label="i.imei" :value="i.id" />
                        </el-select>
                    </el-col>
                    <el-col :span="4">
                        <el-select v-model="wangge" style="width: 100%;" @change="scl()" class="m-2" clearable
                            placeholder="请选择网格" size="large">
                            <el-option v-for="(item, index) in wgList" :key="item + index" :label="item"
                                :value="item" />
                        </el-select>
                    </el-col>
                    <el-col :span="4">
                        <el-select v-model="identifyType" style="width: 100%;" @change="scl()" class="m-2" clearable
                            placeholder="请选择鉴定类型" size="large">
                            <el-option label="未鉴定" value="未鉴定" />
                            <el-option label="已鉴定" value="已鉴定" />
                            <el-option label="无法鉴定" value="无法鉴定" />
                        </el-select>
                    </el-col>
                    <el-col :span="6">
                        <el-date-picker size="large" style="width: 100%;" @change="scl()" v-model="date" clearable
                            type="date" placeholder="选择日期" />
                    </el-col>
                    <el-col :span="6">
                        <el-input v-model="keywords" style="width: 100%;" size="large" placeholder="搜索组编号"
                            class="input-with-select">
                            <template #append>
                                <el-button @click.stop="scl()" :icon="Search" />
                            </template>
                        </el-input>
                    </el-col>
                </el-row>

                <ul class="wls-details-container-right-content">
                    <li class="bcb" v-for="(i, index) in gip ">
                        <div class="wdcrc" :class="i.identifyType == '已鉴定' ? 'wdcrcy' : 'wdcrcw'">
                            <span>{{ i.identifyType }}</span>
                        </div>
                        <div class="wdcrc-img" @click.stop="openLarge(i.urlList)">
                            <video v-if="$wlsf.filiv(i.urlList[0]) == 4" :src="i.urlList[0]" alt=""></video>
                            <img v-else :src="i.urlList[0]" alt="">
                            <div class="wdcrc-time">
                                <span>{{ i.shootingTime }}</span>
                            </div>
                            <div class="wdcrc-num">
                                <i style="margin-right: 0.08rem;" class="icon iconfont icon-zhaopian"></i>
                                <span>{{ i.urlList.length }}张</span>
                            </div>
                        </div>
                        <div class="wdcrc-result">
                            <div>
                                <div><span>网格编号</span></div>
                                <div><span style="color: #AAA;">{{ i.oneKmGridNum }}</span></div>
                            </div>
                            <div style="margin: .08rem 0;">
                                <div><span>相机编号</span></div>
                                <div><span style="color: #AAA;">{{ i.imei }}</span></div>
                            </div>
                            <div style="margin: .08rem 0;">
                                <div><span>AI识别</span></div>
                                <div v-if="i.aiResult != null">
                                    <span style="color: #AAA;">{{ i.aiResult == null ? '' : i.aiResult.split('#')[0]
                                        }}</span>
                                </div>
                                <div v-else>
                                    <span style="color: #AAA;">无识别结果</span>
                                </div>
                            </div>
                            <div>
                                <div><span>鉴定结果</span></div>
                                <div><span style="color: #AAA;">{{ i.identifyResult == null ? '' :
                                    i.identifyResult.split('#')[0] }}</span></div>
                            </div>
                        </div>
                        <div class="wdcrc-com">
                            <div><span style="color: #F84848;" @click.stop="delGroupImgPage(i, index)">删除照片</span></div>
                            <div @click.stop="goaut(i)"><span>前往鉴定</span></div>
                            <div @click.stop="quick(i)"><span
                                    :style="i.aiResult == null ? 'color: #AAA;' : ''">确认AI结果</span></div>
                        </div>
                    </li>
                </ul>

                <el-pagination v-model:current-page="currentPage" :page-size="10" :small="true" :disabled="false"
                    background layout="total, prev, pager, next, jumper" :total="totalElements"
                    @current-change="handleSizeChange" />
            </div>
        </div>


        <!-- 放置相机 B-->
        <wls-popup v-if="isadd">
            <div class="wls-info" style="width: 14rem;">
                <div class="d-lkb-c">
                    <!-- <svg class="wls-icon" aria-hidden="true" @click="resetForm(ruleFormRef)"
                    style="width: .4rem;height: 0.4rem;">
                    <use xlink:href="#icon-guanbi"></use>
                </svg> -->
                    <i class="icon iconfont icon-guanbi" style="font-size: .2rem;" @click="resetForm(ruleFormRef)"></i>
                </div>
                <div class="wls-info-title">
                    <div></div>
                    <div><span>放置相机</span></div>
                </div>
                <div style="height: 0.16rem;"></div>
                <div style="display: flex;overflow: hidden;">
                    <div style="width: 8rem;padding-right: 0.24rem;">
                        <location-map ref="olm" @sendlna="getlna" />
                    </div>
                    <el-form ref="ruleFormRef" :model="ruleForm" label-position="top" class="demo-ruleForm" size="large"
                        status-icon>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="相机编号">
                                    <el-input v-model="ruleForm.imei" placeholder="请输入相机编号" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="标签">
                                    <el-input v-model="ruleForm.label" maxlength="6" placeholder="不能超过六个字符" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="布设人">
                                    <el-select v-model="ruleForm.layUser" style="width: 100%;" class="m-2"
                                        placeholder="请选择布设人" size="large">
                                        <el-option v-for="w in Worker" :key="w[0]" :label="w[1]" :value="w[0]" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="海拔(m)">
                                    <el-input style="width: 100%;" type="number" v-model="ruleForm.altitude" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="布设时间">
                                    <el-date-picker style="width: 100%;" v-model="ruleForm.layTime" type="datetime"
                                        placeholder="请选择布设时间" format="YYYY/MM/DD HH:mm:ss" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="回收时间">
                                    <el-date-picker style="width: 100%;" v-model="ruleForm.planRecovDate"
                                        type="datetime" placeholder="请选择回收时间" format="YYYY/MM/DD HH:mm:ss" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="经度">
                                    <el-input style="width: 100%;" v-model="ruleForm.lon" placeholder="建议点击地图选点" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="纬度">
                                    <el-input style="width: 100%;" v-model="ruleForm.lat" placeholder="建议点击地图选点" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="生境类型">
                                    <el-select v-model="ruleForm.envirType" style="width: 100%;" class="m-2"
                                        placeholder="请选择生境类型" size="large">
                                        <el-option label="常阔" value="常阔" />
                                        <el-option label="常阔混交" value="常阔混交" />
                                        <el-option label="落阔" value="落阔" />
                                        <el-option label="针阔混交" value="针阔混交" />
                                        <el-option label="针叶林" value="针叶林" />
                                        <el-option label="灌丛" value="灌丛" />
                                        <el-option label="草坡" value="草坡" />
                                        <el-option label="流石滩" value="流石滩" />
                                        <el-option label="滩涂" value="滩涂" />
                                        <el-option label="苇塘" value="苇塘" />
                                        <el-option label="水面" value="水面" />
                                        <el-option label="草甸" value="草甸" />
                                        <el-option label="沼泽" value="沼泽" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="小生境">
                                    <el-select v-model="ruleForm.smallEnvir" style="width: 100%;" class="m-2"
                                        placeholder="请选择小生境" size="large">
                                        <el-option label="河边" value="河边" />
                                        <el-option label="林下" value="林下" />
                                        <el-option label="竹林中" value="竹林中" />
                                        <el-option label="草丛" value="草丛" />
                                        <el-option label="树洞" value="树洞" />
                                        <el-option label="岩下" value="岩下" />
                                        <el-option label="公路上" value="公路上" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">
                                保存
                            </el-button>
                            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>

            </div>
        </wls-popup>
        <!-- 放置相机 E-->

        <wls-large :msg="wlm" v-if="iswl" @closeLarge="iswl = false" />
        <wlsUpload ref="wlsupload" @refreshcar="getnewcar" />
    </div>
</template>
<style scoped>
@import '../../assets/wls-aut.css';
</style>